package com.uphone.kingmall.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;


/******************************************
 * 类描述： Fragment基础类 类名称：BaseFragment
 *
 * @version: 1.0
 * @author: sumeng
 * @time: 2018-9-5 16:13
 ******************************************/

public abstract class BaseFragment extends Fragment {
    private static final String TAG = "BaseFragment";
    public final static String TAG_CONNECTOR = "-";
    private String UNIQUE_TAG;
    private int mContainerId;

//    private ImageView mLoadingImageView;
//    private Animation mLoadingAnimation;


    //    private LoadingFailedView mLoadingFailedView;
    private TextView mLoadingFailedTextView;

    /**
     * 是否可以使用butterKnife true为是，false为否
     */
    private boolean canUseButterKnife = true;
    /**
     * 是否可以使用EventBus true为是，false为否
     */
    private boolean canUseEventBus;
    /**
     * 是否需要重新计算加载失败的位置 true为是，false为否
     */
    private boolean canRecalculateLoadingFailedPosition = true;

    /**
     * 状态栏工具
     */
//    protected ImmersionBar mImmersionBar;
    public boolean isImmersionBarEnabled = false;
    private Dialog dialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view1 = LayoutInflater.from(getContext()).inflate(getLayoutContentId(), null);
        try {
            IntentUtils.init(this);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return view1;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }

        initOtherData(view);
        initView(view);
        initData();
//        //订阅接收消息,子类只要重写onEvent就能收到消息
//        JMessageClient.registerEventReceiver(this);
    }

    /**
     * 获取当前Fragment布局ID
     *
     * @return
     */
    public abstract int getLayoutContentId();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 初始化View
     */
    public abstract void initView(View view);

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
//        mImmersionBar = ImmersionBar.with(this);
//        //防止设置状态栏后  软键盘怎么设置也不会把布局顶上去
//        mImmersionBar.keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
//                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN).navigationBarWithKitkatEnable(false).init();
    }

    public void setStatusBar(boolean statusBarDarkFont) {
//        mImmersionBar
//                .statusBarView(statusBar)
//                .statusBarColor(R.color.colorWhite)
//                .statusBarDarkFont(statusBarDarkFont, 0.2f)
//                .navigationBarColor(R.color.colorWhite)
//                .fullScreen(false)
//                .init();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
       /* if(!hidden){
            if((isImmersionBarEnabled())){
                if (mImmersionBar != null){
                    mImmersionBar.init();
                }
            }
        }*/
    }

    @Override
    public void onDestroy() {
        if (canUseEventBus) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
        System.gc();
//        if (mImmersionBar != null)
//            mImmersionBar.destroy();
    }

    /**
     * 是否在Fragment使用沉浸式
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return isImmersionBarEnabled;
    }

    /**
     * 启用EventBus功能
     */
    protected void enableEventBus() {
        canUseEventBus = true;
    }

    /**
     * 禁用butterKnife功能
     */
    protected void disableButterKnife() {
        canUseButterKnife = false;
    }

    /**
     * 禁用重新计算加载失败位置
     */
    protected void disableRecalculateLoadingFailedPosition() {
        canRecalculateLoadingFailedPosition = false;
    }

    /**
     * 初始化其他辅助业务逻辑
     */
    private void initOtherData(View view) {
        if (canUseButterKnife) {
            ButterKnife.bind(this, view);
        }
        if (canUseEventBus) {
            EventBus.getDefault().register(this);
        }
    }

    public String getUniqueTag() {
        if (UNIQUE_TAG == null) {
            StringBuilder stringBuilder = new StringBuilder();
            UNIQUE_TAG = stringBuilder.append(getClass().getName()).append(TAG_CONNECTOR).append(hashCode()).toString();
        }
        return UNIQUE_TAG;
    }

    public int getContainerId() {
        return mContainerId;
    }

    public void setContainerId(int containerId) {
        this.mContainerId = containerId;
    }

    public boolean onBackPressed() {
        return false;
    }

    /**
     * 获取一个安全的Context如果需要使用KaolaBaseFragmentActivity需要自行处理所返回实例是否为自己所需实例
     *
     * @return
     */
    public Context getActivitySafely() {
        Context context = getActivity();
        if (context == null) {
            return MyApplication.mContext;
        }
        return context;
    }

    /**
     * 通过一种更合适的方式获取Res对象
     *
     * @return
     */
    public Resources getResourcesSafely() {
        return getActivitySafely().getResources();
    }

    /**
     * Fragment动画开始执行回调
     *
     * @param enter
     * @param animation
     */
    protected void onFragmentAnimationStart(boolean enter, Animation animation) {
    }

    /**
     * Fragment动画执行完毕回调
     *
     * @param enter
     * @param animation
     */
    protected void onFragmentAnimationEnd(boolean enter, Animation animation) {
    }

    @Override
    public Animation onCreateAnimation(int transit, final boolean enter, int nextAnim) {
        Animation anim = null;
        try {
            anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);
        } catch (Exception e) {
        }
        if (anim == null) {
            onFragmentAnimationEnd(enter, null);
            return null;
        }
        anim.setAnimationListener(new Animation.AnimationListener() {
            //动画开始
            @Override
            public void onAnimationStart(Animation animation) {
                onFragmentAnimationStart(enter, animation);
            }

            //动画循环
            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            //动画结束
            @Override
            public void onAnimationEnd(final Animation animation) {
                View v = getView();
                if (v != null) {
                    v.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (isAdded()) {
                                onFragmentAnimationEnd(enter, animation);
                            }
                        }
                    }, 100);
                }
            }
        });
        return anim;
    }

    /**
     * 启动Activity
     *
     * @param intent
     */
    @Override
    public void startActivity(Intent intent) {
        Context context = getActivitySafely();
        context.startActivity(intent);
    }

    /**
     * 不带参跳转
     *
     * @param targetActivityClass
     */
    public void openActivity(Class<?> targetActivityClass) {
        FragmentActivity activity = getActivity();
        Intent intent = new Intent();
        intent.setClass(activity, targetActivityClass);
        startActivity(intent);
    }

    /**
     * 带参跳转
     *
     * @param targetActivityClass
     * @param bundle
     */
    public void openActivity(Class<?> targetActivityClass, Bundle bundle) {
        FragmentActivity activity = getActivity();
        Intent intent = new Intent(activity, targetActivityClass);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 检测用户是否登录
     *
     * @return true为登录，false未登录
     */
    public boolean canShowLoginPage() {
//        if (UserHelper.getInstance().isUserLogin()) {
//            return false;
//        } else {
//            Activity activity = getActivity();
//            Intent intent = new Intent(activity, LoginActivity.class);
//            activity.startActivity(intent);
//            return true;
//        }
        return false;
    }

    //Toast显示
    protected void showShortToast(String string) {
        ToastUtils.showShortToast(getActivitySafely(), string);
    }

    protected void showShortToast(int stringId) {
        ToastUtils.showShortToast(getActivitySafely(), stringId);
    }

    protected void showLongToast(String string) {
        ToastUtils.showShortToast(getActivitySafely(), string);
    }

    protected void showLongToast(int stringId) {
        ToastUtils.showShortToast(getActivitySafely(), stringId);
    }

    //    public void onEventMainThread(LoginStateChangeEvent event) {
//        final LoginStateChangeEvent.Reason reason = event.getReason();
//        UserInfo myInfo = event.getMyInfo();
//        if (myInfo != null) {
//            String path;
//            File avatar = myInfo.getAvatarFile();
//            if (avatar != null && avatar.exists()) {
//                path = avatar.getAbsolutePath();
//            } else {
//                path = FileHelper.getUserAvatarPath(myInfo.getUserName());
//            }
//            SharePreferenceManager.setCachedUsername(myInfo.getUserName());
//            SharePreferenceManager.setCachedAvatarPath(path);
//            JMessageClient.logout();
//        }
//        switch (reason) {
//            case user_logout:
//                View.OnClickListener listener = new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        switch (v.getId()) {
//                            case R.id.jmui_cancel_btn:
//                                Intent intent = new Intent(mContext, LoginActivity.class);
//                                startActivity(intent);
//                                break;
//                            case R.id.jmui_commit_btn:
//                                String str = SharedPreferencesHelper.getImuid();
//                                if(TextUtils.isEmpty(str)){
//                                    jimRegister();
//                                }else{
//                                    JMessageClient.login(str, str, new BasicCallback() {
//                                        @Override
//                                        public void gotResult(int responseCode, String responseMessage) {
//                                            if (responseCode == 0) {
//                                                Intent intent = new Intent(mContext, MainActivity.class);
//                                                startActivity(intent);
//                                            }
//                                        }
//                                    });
//                                }
//
//                                break;
//                        }
//                    }
//                };
//                dialog = DialogCreator.createLogoutStatusDialog(mContext, "您的账号在其他设备上登陆", listener);
//                dialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
//                dialog.setCanceledOnTouchOutside(false);
//                dialog.setCancelable(false);
//                dialog.show();
//                break;
//            case user_password_change:
//                Intent intent = new Intent(mContext, LoginActivity.class);
//                startActivity(intent);
//                break;
//        }
//    }
    public void loadJPush() {
    }
}
